from handlers.base import BaseHandler
from tornado.web import asynchronous
from tornado.gen import coroutine
import json
import time

class LoginHandler(BaseHandler):
	@asynchronous
	@coroutine
	def post(self):
		data = self.get_argument("data")
		data = json.loads(data)
		email = data['email']
		passwd = data['pass']
		user = yield self.db.user.find_one({"email" : email})
		if(not user):
			return self.write("not_user")
		check = yield self.db.user.find_one({"passwd" : passwd})
		if(check):
			self.session['current_session'] = email
			return self.write("success")
		self.write("error")

class RegisterHandler(BaseHandler):
	def get(self):
		self.write("register")
	@asynchronous
	@coroutine
	def post(self):
		data = self.get_argument("user")
		data = json.loads(data)
		email = data['email']
		has_email = yield self.db.user.find_one({'email':email})
		if(has_email):
			return self.write("has")
		
		passwd = data['passwd']
		user = {
			'email': email,
			'passwd': passwd,
			'uname': "",
			'signal':"",
			'img': "",
			'token': "",
			'creat_time': time.time(),
			'power': 0
		}
		res = yield self.db.user.insert(user)
		if(res):
			return self.write("success")
		self.write("error")